/**
 * 
 */
package com.novatialabs.qttt.gwt.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;

/**
 * @author nchalko
 * 
 */
public class QuantumBoardWidget extends Composite implements HasMarkHandlers, GameDisplayHandler {

  public class CellClickHandler implements ClickHandler {
    private final int cellNumber;

    public CellClickHandler(int cellNumber) {
      this.cellNumber = cellNumber;
    }

    public void onClick(ClickEvent event) {
      fireEvent(new MarkEvent(cellNumber));
    }

  }

  GameCellWidget[] cells = new GameCellWidget[9];

  public QuantumBoardWidget() {

    Grid grid = new Grid(3, 3);
    for (int i = 0; i < cells.length; i++) {
      cells[i] = new GameCellWidget(i + 1);
      grid.setWidget(i / 3, i % 3, cells[i]);
      createClickHandler(cells[i]);

    }
    initWidget(grid);
    setStylePrimaryName("quantum_board");

  }

  private void createClickHandler(GameCellWidget gameCellWidget) {
    final int cellNumber = gameCellWidget.getCellNumber();
    gameCellWidget.addClickHandler(new CellClickHandler(cellNumber));

  }

  public HandlerRegistration addMarkHandler(MarkHandler handler) {
    return addHandler(handler, MarkEvent.getType());
  }

  public void display(GameModel game) {
    for (GameCellWidget cell : cells) {
      cell.display(game);
    }
  }

  public void display(GameDisplayEvent gameEvent) {
    display(gameEvent.getGame());

  }

}
